﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;

namespace XExcel
{
    /// <summary>
    /// 读CSV文件类,读取指定的CSV文件
    /// </summary>
    public static class CsvReader
    {
        /// <summary>
        /// 加载csv
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="withHeader">是否包含标题行</param>
        public static DataTable Load(string content, bool withHeader = true, char separator = ',')
        {
            //对数据的有效性进行验证
            if(string.IsNullOrWhiteSpace(content))
            {
                throw new Exception("指定要载入的内容无效。");
            }
            CsvHelper.CheckSeparator(separator);

            var lines = content.Split("\r\n".ToCharArray());
            return Load(lines, withHeader, separator);
        }

        /// <summary>
        /// 加载csv
        /// </summary>
        /// <param name="fileName">文件名,包括文件路径</param>
        /// <param name="encoding">文件编码</param>
        /// <param name="withHeader">是否包含标题行</param>
        public static DataTable Load(string fileName, Encoding encoding, bool withHeader = true, char separator = ',')
        {
            //对数据的有效性进行验证
            if(string.IsNullOrWhiteSpace(fileName))
            {
                throw new Exception("请指定要载入的CSV文件名。");
            }
            else if(!File.Exists(fileName))
            {
                throw new Exception("指定的CSV文件不存在。");
            }
            CsvHelper.CheckSeparator(separator);

            using(var stream = new StreamReader(fileName, encoding))
            {
                var lines = new StreamLines(stream).Read();
                return Load(lines, withHeader, separator);
            }
        }

        /// <summary>
        /// 加载csv
        /// </summary>
        /// <param name="fileName">文件名,包括文件路径</param>
        /// <param name="encoding">文件编码</param>
        /// <param name="withHeader">是否包含标题行</param>
        public static DataTable Load(StreamReader stream, bool withHeader = true, char separator = ',')
        {
            //对数据的有效性进行验证
            if(stream == null)
            {
                throw new Exception("请指定要载入的CSV流。");
            }
            CsvHelper.CheckSeparator(separator);

            var lines = new StreamLines(stream).Read();
            return Load(lines, withHeader, separator);
        }

        class StreamLines
        {
            private readonly StreamReader stream;

            public StreamLines(StreamReader stream)
            {
                this.stream = stream;
            }

            public IEnumerable<string> Read()
            {
                while(!stream.EndOfStream)
                {
                    yield return stream.ReadLine();
                }
            }
        }

        /// <summary>
        /// 载入CSV文件
        /// </summary>
        private static DataTable Load(IEnumerable<string> lines, bool withHeader, char separator)
        {
            var rows = new List<List<string>>();
            var table = new DataTable();
            string csvDataLine = "";
            foreach(var line in lines)
            {
                if(line == null)
                {
                    break;
                }
                if(csvDataLine == "")
                {
                    csvDataLine = line;//GetDeleteQuotaDataLine(fileDataLine);
                }
                else
                {
                    csvDataLine += "\\r\\n" + line;//GetDeleteQuotaDataLine(fileDataLine);
                }
                //如果包含偶数个引号，说明该行数据中出现回车符或包含逗号
                if(!IfOddQuota(csvDataLine))
                {
                    var cells = LoadRow(csvDataLine, separator);
                    rows.Add(cells);
                    csvDataLine = "";
                }
            }

            //数据行出现奇数个引号
            if(csvDataLine.Length > 0)
            {
                throw new Exception("CSV文件的格式有错误。");
            }

            if(rows.Count == 0)
            {
                return table;
            }

            var firstRow = rows[0];
            var colCount = firstRow.Count;
            for(var i = 0; i < firstRow.Count; i++)
            {
                if(withHeader)
                {
                    table.Columns.Add(firstRow[i]);
                }
                else
                {
                    table.Columns.Add(i.ToString());
                }
            }
            var rowIndex = 0;
            if(withHeader)
            {
                rowIndex = 1;
            }
            for(var row = rowIndex; row < rows.Count; row++)
            {
                DataRow csvDR = table.NewRow();
                for(int i = 0; i < rows[row].Count && i < colCount; i++)
                {
                    csvDR[i] = rows[row][i];
                }
                table.Rows.Add(csvDR);
            }
            return table;
        }

        /// <summary>
        /// 加入新的数据行
        /// </summary>
        /// <param name="newDataLine">新的数据行</param>
        private static List<string> LoadRow(string newDataLine, char separator)
        {
            var cells = new List<string>();
            string[] dataArray = newDataLine.Split(separator);
            bool oddStartQuota;        //是否以奇数个引号开始
            string cellData;
            oddStartQuota = false;
            cellData = "";
            for(int i = 0; i < dataArray.Length; i++)
            {
                if(oddStartQuota)
                {
                    //因为前面用逗号分割,所以要加上逗号
                    cellData += separator + dataArray[i];
                    //是否以奇数个引号结尾
                    if(IfOddEndQuota(dataArray[i]))
                    {
                        cells.Add(LoadCell(cellData));
                        oddStartQuota = false;
                        continue;
                    }
                }
                else
                {
                    //是否以奇数个引号开始
                    if(IfOddStartQuota(dataArray[i]))
                    {
                        //是否以奇数个引号结尾,不能是一个双引号,并且不是奇数个引号
                        if(IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2 && !IfOddQuota(dataArray[i]))
                        {
                            cells.Add(LoadCell(dataArray[i]));
                            oddStartQuota = false;
                            continue;
                        }
                        else
                        {
                            oddStartQuota = true;
                            cellData = dataArray[i];
                            continue;
                        }
                    }
                    else
                    {
                        cells.Add(LoadCell(dataArray[i]));
                    }
                }
            }

            if(oddStartQuota)
            {
                throw new Exception("数据格式有问题");
            }
            return cells;
        }

        /// <summary>
        /// 去掉格子的首尾引号，把双引号变成单引号
        /// </summary>
        /// <param name="fileCellData"></param>
        /// <returns></returns>
        private static string LoadCell(string fileCellData)
        {
            if(fileCellData == "")
            {
                return "";
            }

            if(IfOddStartQuota(fileCellData))
            {
                if(IfOddEndQuota(fileCellData))
                {
                    return fileCellData.Substring(1, fileCellData.Length - 2).Replace("\"\"", "\""); //去掉首尾引号，然后把双引号变成单引号
                }
                else
                {
                    throw new Exception("数据引号无法匹配" + fileCellData);
                }
            }
            else
            {
                //考虑形如""    """"      """"""   
                if(fileCellData.Length > 2 && fileCellData[0] == '\"')
                {
                    fileCellData = fileCellData.Substring(1, fileCellData.Length - 2).Replace("\"\"", "\""); //去掉首尾引号，然后把双引号变成单引号
                }
            }
            return fileCellData;
        }

        /// <summary>
        /// 获取两个连续引号变成单个引号的数据行
        /// </summary>
        /// <param name="fileDataLine">文件数据行</param>
        /// <returns></returns>
        private static string GetDeleteQuotaDataLine(string fileDataLine)
        {
            return fileDataLine.Replace("\"\"", "\"");
        }

        /// <summary>
        /// 判断字符串是否包含奇数个引号
        /// </summary>
        /// <param name="dataLine">数据行</param>
        /// <returns>为奇数时，返回为真；否则返回为假</returns>
        private static bool IfOddQuota(string dataLine)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for(int i = 0; i < dataLine.Length; i++)
            {
                if(dataLine[i] == '\"')
                {
                    quotaCount++;
                }
            }
            oddQuota = false;
            if(quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }

        /// <summary>
        /// 判断是否以奇数个引号开始
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private static bool IfOddStartQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for(int i = 0; i < dataCell.Length; i++)
            {
                if(dataCell[i] == '\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if(quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }

        /// <summary>
        /// 判断是否以奇数个引号结尾
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private static bool IfOddEndQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for(int i = dataCell.Length - 1; i >= 0; i--)
            {
                if(dataCell[i] == '\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if(quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }
    }
}